import React, { Component } from 'react';
import { Text, View, TouchableOpacity, ScrollView, Platform, KeyboardAvoidingView, StyleSheet, Image, Alert } from "react-native";
import { GLOBAL } from '../../../../config/global';
import { FormItem } from '../../../../components/form/formItem';
import Dictionary from '../../../../utils/dictionary';
import { Button } from '../../../../components/form/button';
import { Common } from '../../../../component/common/Common.js';
import { style } from '../../../../theme/style';
import { AddressCpt } from '../_components/AddressCpt';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import { orderBlockStyle } from '../_common/style';
import ProductSelect from '../../../product/modals/ProductSelect';
import HTTP from '../../../../utils/http';
import { API, API_GENERATE } from '../../../../config/api';
import ToastUtil from '../../../../utils/toast';
import MethodUtil from '../../../../utils/MethodUtil';
import { CURRENCY } from '../../../../utils/helper';
import OrderCreactService from '../_common/service';
import moment from 'moment';
import { RadiusGroupCpt } from '../_components/RadiusGroupCpt';
const checkOnImg = require('../../../../imgs/checkOn.png');
const checkOffImg = require('../../../../imgs/checkOff.png');
const scale = GLOBAL.SCALE;
const InfoIcon = require('../../../../imgs/global/query.png');
const currentMonth = moment().format('YYYYMM');
const nextMonth = moment().add('months', 1).format('YYYYMM');
const quantityReg = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,3})?$/;


export class HistoryOrderInfoPage extends Component {
    static navigationOptions = ({ navigation, navigationOptions }) => {
        return {
            headerTitle: '泉化销售',
            headerTintColor: style.color.white,
            headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
            headerTitleStyle: {
                flex: 1,
                textAlign: 'center'
            },
            headerStyle: style.head.headerStyle,
        }
    };

    constructor(props) {
        super(props);
        this.state = {
            status: 'data',
            goodsModal: false,
        }
        this.resetPage = OrderCreactService.reset.bind(this);
        let { orderIdList } = props.navigation.state.params;
        this.orderIdList = orderIdList || [];
        this.orderList = [];
        this.currentIndex = ''; // 当前点击的商品
        this.getPriceFlag = true;
        // 当前商品的框架id
        this.currentParams = {
            orderId: ''
        }
        // 当前选中的商品
        this.currentGoodsInfo = []
    }

    async	componentWillMount() {
        let { orderList, orderIdList } = this.props.navigation.state.params;
        // 当前页面新增历史订单，已经存在的订单不做修改，只请求新增的订单
        if (orderList && orderList.length > 0) {
            let newIdList = JSON.parse(JSON.stringify(orderIdList));
            let newOrderList = JSON.parse(JSON.stringify(orderList));
            this.orderIdList.forEach((itemId) => {
                newOrderList.forEach(orderItem => {
                    if (itemId == orderItem.orderInfo.orderId) {
                        this.orderList.push(orderItem);
                        let index = newIdList.indexOf(itemId);
                        if (index != -1) newIdList.splice(index, 1)
                    }
                })
            })
            if (newIdList && newIdList.length > 0) this.initPage(newIdList);
        } else {
            this.initPage(this.orderIdList)
        }
    }

    initPage = async (orderIdList) => {
        orderIdList.forEach(async (orderId) => {
            this.setState({ status: 'loading' })
            let res = await HTTP.POST(API_GENERATE(API.FIND_ORDER_E), { orderId });
            if (res) {
                let data = await this.dealInfo(res);
                if (data && data.orderInfo) {
                    data.orderInfo.orderIdOld = data.orderInfo.orderId;
                }
                this.orderList.push(data);
            }
            this.setState({ status: 'data' });
        })
    }

    // 数据处理
    dealInfo = async (data) => {
        let orderItem = data;
        orderItem.orderItemList[0].quantity = '';
        orderItem.orderItemList[0].suggestedPrice = '';
        let orderPlanMonth = orderItem.orderItemList[0].orderPlanMonth;
        orderItem.orderItemList[0].orderPlanMonth = orderPlanMonth == nextMonth ? nextMonth : currentMonth;
        orderItem.goodsQuantity = await this.getGoodsQuantity(orderItem);
        return orderItem
    }

    // 计算订单总额
    getTotalPrice = async (index, item) => {
        let { orderId, logisticsPrice, orderIdOld } = item.orderInfo;
        let { itemId, goodsId, quantity, udPrice } = item.orderItemList[0];
        // if (quantity == '') return
        let subData = {
            orderId: orderIdOld || orderId,
            orderItemInfo: {
                orderId: orderIdOld || orderId,
                itemId,
                goodsId,
                longOrderId: orderIdOld || orderId,
            }
        }
        let res = await HTTP.POST(API_GENERATE(API.ORDER_OTHER_PRICE), subData);
        if (res) {
            let rebatePrice = res.rebatePrice || 0;
            let suggestedPrice = res.suggestedPrice || 0;
            let params = {};
            params.rebatePrice = "-" + rebatePrice;
            params.suggestedPrice = suggestedPrice;
            item.orderItemList[0].price = suggestedPrice;
            //params.udPrice = udPrice || 0;
            params.logisticsPrice = logisticsPrice;

            let price = 0; // 单价
            price = this.multiAdd(params);
            item.orderItemList[0].price = price;

            let totalAmount = MethodUtil.countObj.multiply(price, Number.parseFloat(quantity || '0'));
            this.orderList[index].totalAmount = totalAmount;
            this.orderList[index].orderItemList[0].suggestedPrice = res.suggestedPrice || 0;
            this.orderList[index].orderItemList[0].rebatePrice = res.rebatePrice || 0;
            this.orderList[index].totalQuantity = this.orderList[index].orderItemList[0].quantity; // 数量
            this.setState({ status: 'data' })
        } else {
            this.orderList[index].orderItemList[0].suggestedPrice = null
            this.orderList[index].totalQuantity = null
            this.orderList[index].totalAmount = null;
            this.setState({ status: 'data' })
        }
    }

    multiAdd = (params) => {
        let sumData = 0;
        for (const value in params) {
            sumData = MethodUtil.countObj.add(Number.parseFloat(params[value] || '0'), sumData)
        }
        return sumData;
    }

    // 提交
    submit = async (submit) => {
        if (!this.formVerify()) return;
        if (!this.getPriceFlag) return;
        this.setState({ status: 'loading' })
        this.submitInfo = JSON.parse(JSON.stringify(this.orderList));
        this.submitInfo.forEach(item => {
            item.orderInfo.orderId = '';
            item.orderItemList[0].itemId = '';
        })
        console.log('submit清除orderId', this.submitInfo)
        let api = submit ? API.QH_SUBMIT_ALL : API.QH_SAVE_ALL;
        let res = await HTTP.POST(API_GENERATE(api), { orderList: this.submitInfo });
        this.setState({ status: 'data' })
        if (res) {
            ToastUtil.showSuccess(submit ? '提交成功' : '保存成功').then(() => {
                this.resetPage('S', 'QH', submit ? 2 : 0);
            })
        }
    }

    // 表单验证
    formVerify = () => {
        for (let i = 0; i < this.orderList.length; i++) {
            let orderInfo = this.orderList[i].orderInfo;
            let goodsInfo = this.orderList[i].orderItemList[0];
            let index = i + 1;
            let { remainPlanQuantity, stockQuantity, stockPlanQuantityMax, longQuantity, remainLongQuantity } = this.orderList[i].goodsQuantity;
            if (!goodsInfo.quantity) {
                ToastUtil.showWarning(`请填写第${index}个订单数量`);
                return
            }
            if (goodsInfo.quantity <= 0) {
                ToastUtil.showWarning(`第${index}个订单数量不能小于等于0`);
                return
            }
            if (!quantityReg.test(goodsInfo.quantity)) {
                ToastUtil.showWarning(`请输入第${index}个订单正确的数量(最多3位小数)`, 1300);
                return
            }
            if (!goodsInfo.suggestedPrice || goodsInfo.suggestedPrice <= 0) {
                ToastUtil.showWarning(`第${index}商品暂无今日现货价`, 1300);
                return
            }
            if (!remainPlanQuantity || goodsInfo.quantity > remainPlanQuantity) {
                ToastUtil.showWarning(`第${index}个订单的数量已超出计划量`, 1300);
                return
            }
            // if (!stockQuantity || goodsInfo.quantity > stockQuantity) {
            //   ToastUtil.showWarning(`第${index}个订单的数量已超出库存`, 1300);
            //   return
            // }
            if (!longQuantity || goodsInfo.quantity > longQuantity) {
                ToastUtil.showWarning(`第${index}个订单的数量已超出执行量`, 1300);
                return
            }
            if (!remainLongQuantity || goodsInfo.quantity > remainLongQuantity) {
                ToastUtil.showWarning(`第${index}个订单的数量已超出剩余量`, 1300);
                return
            }
            if ((orderInfo.deliveryType === 'P' || orderInfo.deliveryType === 'S') && !orderInfo.destAddressId) {
                ToastUtil.showWarning(`请选择第${index}个订单的地址`);
                return
            }
        }
        return true
    }

    // 删除
    delete = (index) => {
        let orderId = this.orderList[index].orderInfo.orderId;
        this.orderList.splice(index, 1);
        this.orderIdList.splice(this.orderIdList.indexOf(orderId), 1);
        ToastUtil.showWarning('删除成功');
        this.setState({ status: 'data' });
    }

    // 跳转详情页编辑
    goDetailPage = (index, item) => {
        this.props.navigation.navigate('orderBasePage', {
            orderIndex: index,
            orderInfo: item,
            orderType: item.orderInfo.orderType,
            tCode: 'QH',
            batch: true,
            _detailCallback: this._detailCallback
        })
    }

    // 详情页保存回填
    _detailCallback = async (index, item) => {
        this.setState({ status: 'loading' })
        this.orderList[index] = item;
        this.orderList[index].goodsQuantity = await this.getGoodsQuantity(item);
        this.getTotalPrice(index, item);
        this.setState({ status: 'data' });
    }

    // 点击商品选择
    selectProduct = (index, orderInfo, goodsInfo) => {
        this.currentParams.orderId = orderInfo.longOrderId;
        this.currentIndex = index;
        this.currentGoodsInfo = [];
        if (goodsInfo.goodsId) this.currentGoodsInfo.push({ goodsId: goodsInfo.goodsId, goodsName: goodsInfo.goodsName })
        this.setState({ goodsModal: true })
    }

    // 选择商品回填
    _confirmPress = async (data) => {
        if (data.length > 0) {
            this.orderList[this.currentIndex].orderItemList[0].goodsId = data[0].goodsId;
            this.orderList[this.currentIndex].orderItemList[0].goodsName = data[0].goodsName;
            this.orderList[this.currentIndex].goodsQuantity = await this.getGoodsQuantity(this.orderList[this.currentIndex]);
            this.getTotalPrice(this.currentIndex, this.orderList[this.currentIndex])
            this.setState({ goodsModal: false })
        } else {
            this.setState({ goodsModal: false })
        }
    }

    _cancelPress = () => {
        this.setState({ goodsModal: false })
    }

    // 输入数量
    _quantityFn = (str, index, item) => {
        this.orderList[index].orderItemList[0].quantity = str;
        this.getPriceInterval(index, item)
    }

    // 请求数量节流
    getPriceInterval = (index, item) => {
        if (!this.getPriceFlag) return
        this.getPriceFlag = false;
        setTimeout(async () => {
            await this.getTotalPrice(index, item);
            this.getPriceFlag = true;
        }, 800)
    }

    // 使用下月计划量
    selectNextMonthQuantity = async (index) => {
        this.setState({ status: 'loading' });
        let orderPlanMonth = this.orderList[index].orderItemList[0].orderPlanMonth;
        this.orderList[index].orderItemList[0].orderPlanMonth = orderPlanMonth == currentMonth ? nextMonth : currentMonth;
        this.orderList[index].goodsQuantity = await this.getGoodsQuantity(this.orderList[index]);
        this.setState({ status: 'data' });
    }

    // 地址回填
    _addressCallback = (params) => {
        this.orderList[params.index].orderInfo.destAddressId = params.addrId;
        this.orderList[params.index].orderInfo.destAddress = params.value;
        this.setState({ status: 'data' })
    }

    _renderAddressSelect = (addressParams) => {
        let { index, title, id, info, value, orderType, tCode, deliveryType, companyId, companyName } = addressParams;
        return (
            <AddressCpt data={{
                index, id, title, info, value,
                navigation: this.props.navigation,
                paramsData: {
                    tCode, orderType, companyId, deliveryType,
                    companyName
                },
                addressCallback: this._addressCallback,
            }} />
        )
    }

    // 运费单价
    _priceFn = (str, index, item) => {
        this.orderList[index].orderInfo.logisticsPrice = str;
        this.getPriceInterval(index, item)
    }

    // 获取商品数量
    getGoodsQuantity = async (orderItem) => {
        let { longOrderId, orderType, isUnite, companyId } = orderItem.orderInfo;
        let { orderPlanMonth, goodsId, longItemId } = orderItem.orderItemList[0];
        let params = {
            orderId: longOrderId, companyId,
            orderType, isUnite, orderPlanMonth, goodsId, itemId: longItemId
        }
        let res = await HTTP.POST(API_GENERATE(API.GET_FRAME_GOODS_QUANTITY), params);
        return res || null;
    }

    showMoreInfo = (index) => {
        if (!this.orderList[index].goodsQuantity) return
        let month = this.orderList[index].orderItemList[0].orderPlanMonth;
        let monthText = month == currentMonth ? '当月' : '下月';
        let { remainPlanQuantity, stockQuantity, stockPlanQuantityMax, longQuantity, remainLongQuantity } = this.orderList[index].goodsQuantity;
        Alert.alert('提示',
            `${monthText}剩余计划量：${remainPlanQuantity || '--'}吨；分公司敞口库存：${stockQuantity || '--'}吨， 敞口上限：${stockPlanQuantityMax || '--'}吨；长约总量：${longQuantity || '--'}吨， 剩余量：${remainLongQuantity || '--'}吨；`,
            [{ text: '确认' },]
        );
    }

    addMoreItem = () => {
        this.props.navigation.state.params.historyListcallBack({
            orderIdList: this.orderIdList,
            qhOrderList: this.orderList
        });
        this.props.navigation.goBack()
    }

    render() {
        let { status, goodsModal } = this.state;
        return (
            <KeyboardAvoidingView style={styles.container} behavior={Platform.OS === 'ios' ? 'padding' : null} keyboardVerticalOffset={74}>
                <ScrollView style={styles.scrollWrap} keyboardShouldPersistTaps={'handled'} showsVerticalScrollIndicator={false}>
                    <TouchableOpacity style={styles.addMoreBtn} activeOpacity={.8} onPress={() => this.addMoreItem()}>
                        <Text style={{ fontSize: 13 * scale, color: '#fff' }}>新增历史订单</Text>
                    </TouchableOpacity>

                    {
                        this.orderList && this.orderList.map((item, index) => {
                            let orderInfo = item.orderInfo;
                            let goodsInfo = item.orderItemList[0];
                            let { label, text } = CURRENCY.getUnit(orderInfo.currency);
                            let unitText = text;
                            return (
                                <View key={index} style={styles.formItem}>
                                    <Text style={{ fontSize: 13 * scale, marginBottom: 10 * scale }}>{orderInfo.longOrderId}</Text>
                                    <View style={{ flexDirection: 'row', alignContent: 'center' }}>
                                        <View style={styles.count}>
                                            <Text style={{ fontSize: 12 * scale, opacity: .6 }}>{index + 1}</Text>
                                        </View>
                                        <TouchableOpacity activeOpacity={.8} style={{ flex: 1 }} onPress={() => { this.goDetailPage(index, item) }}>
                                            <Text numberOfLines={1} style={{ flex: 1, color: '#148CFB' }}>{orderInfo.companyName}</Text>
                                        </TouchableOpacity>
                                        {
                                            this.orderList.length > 1 ? (
                                                <TouchableOpacity activeOpacity={.8} onPress={() => { this.delete(index) }}>
                                                    <Text style={{ fontSize: 13 * scale, opacity: .5 }}>删除</Text>
                                                </TouchableOpacity>
                                            ) : null
                                        }
                                    </View>

                                    <View style={{ paddingTop: 10 * scale }}>
                                        <FormItem type={'select'} label={goodsInfo.goodsName} handleCallBack={() => { this.selectProduct(index, orderInfo, goodsInfo) }} />
                                        <View style={{ position: 'relative' }}>
                                            <FormItem sizeType={'small'} border keyboardType='numeric' type={'input'} label={'数量'} value={goodsInfo.quantity} placeHolder={`请输入数量`} handleCallBack={(str) => { this._quantityFn(str, index, item) }} required />
                                            {/* 商品数量展示 */}
                                            <TouchableOpacity style={styles.moreInfo} activeOpacity={.8} onPress={() => { this.showMoreInfo(index) }}>
                                                <Image style={{ width: 14 * scale, height: 14 * scale }} source={InfoIcon} />
                                            </TouchableOpacity>
                                            {/* 下月采购 */}
                                            <TouchableOpacity activeOpacity={.6} style={styles.selectWrap} onPress={() => { this.selectNextMonthQuantity(index) }}>
                                                <Image style={{ marginRight: 4 * scale }} source={goodsInfo.orderPlanMonth == nextMonth ? checkOnImg : checkOffImg} />
                                                <Text style={goodsInfo.orderPlanMonth == nextMonth ? { opacity: 1 } : { opacity: .65 }}>使用下月</Text>
                                            </TouchableOpacity>
                                        </View>
                                        <View>
                                            {orderInfo.deliveryType === 'P' || orderInfo.deliveryType === 'S' ? this._renderAddressSelect({
                                                title: '目的地',
                                                id: 'destAddressId',
                                                value: orderInfo.destAddress,
                                                info: (orderInfo.deliveryType == 'P' || orderInfo.deliveryType == 'S') ? '落合同' : false,
                                                orderType: orderInfo.orderType,
                                                tCode: 'QH',
                                                deliveryType: orderInfo.deliveryType,
                                                companyId: orderInfo.companyId,
                                                companyName: orderInfo.companyName,
                                                index,
                                            }) : this._renderAddressSelect({
                                                title: '出库地',
                                                value: '中化泉化厂库',
                                                tCode: 'QH',
                                            })}
                                        </View>

                                        <FormItem border keyboardType='numeric' type={'input'} label={'运费单价'} value={orderInfo.logisticsPrice} placeHolder={`请输入运费单价`} handleCallBack={(str) => { this._priceFn(str, index, item) }} required />
                                        {/* <View style={styles.totalPrice}>
                      <Text style={{ fontSize: 13 * scale, opacity: .65 }}>合计数量：</Text>
                      <Text style={{ fontSize: 13 * scale }}>{item.totalQuantity || '--'}吨</Text>
                    </View> */}
                                        <View style={styles.totalPrice}>
                                            <Text style={{ fontSize: 13 * scale, opacity: .65 }}>订单总额：</Text>
                                            <Text style={{ fontSize: 13 * scale }}>{item.totalAmount || '--'}{unitText}</Text>
                                        </View>
                                    </View>
                                </View>
                            )
                        })
                    }
                </ScrollView>

                <View style={styles.btnWarp}>
                    <Button type={'outline'} text={'保存'} width={140} height={34} onPress={() => { this.submit() }} />
                    <Button text={'提交'} width={140} height={34} onPress={() => { this.submit(true) }} />
                </View>

                {
                    goodsModal ? (<ProductSelect
                        confirmPress={this._confirmPress}
                        cancelPress={this._cancelPress}
                        sendData={this.currentParams}
                        mainCheckData={this.currentGoodsInfo}
                        tCode={'QH'}
                        modalVisible={goodsModal} />) : null
                }

                {
                    status != 'data' ? (<View style={orderBlockStyle.statusStyle}><PageStatusIndex status={status} /></View>) : null
                }
            </KeyboardAvoidingView>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5F5F5',
    },
    addMoreBtn: {
        width: 108 * scale,
        height: 28 * scale,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#148CFB',
        borderRadius: 17 * scale,
        marginTop: 14 * scale,
        marginBottom: 8 * scale
    },
    scrollWrap: {
        paddingLeft: 12 * scale,
        paddingRight: 12 * scale,
    },
    btnWarp: {
        paddingLeft: 12 * scale,
        paddingRight: 12 * scale,
        height: 72 * scale,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-around',
    },
    formItem: {
        backgroundColor: '#fff',
        borderRadius: 4 * scale,
        paddingLeft: 12 * scale,
        paddingRight: 12 * scale,
        paddingTop: 12 * scale,
        paddingBottom: 12 * scale,
        marginBottom: 18 * scale,
    },
    count: {
        width: 16 * scale,
        height: 16 * scale,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 8 * scale,
        backgroundColor: 'rgba(39,39,39, .09)',
        marginRight: 6 * scale
    },
    info: {
        color: '#F66464',
        fontSize: 13 * scale,
        marginBottom: 8 * scale,
        marginTop: 8 * scale
    },
    totalPrice: {
        paddingTop: 10 * scale,
        flexDirection: 'row',
        justifyContent: 'flex-end',
        alignItems: 'center'
    },
    moreInfo: {
        position: 'absolute',
        left: 56 * scale,
        top: 12 * scale,
        zIndex: 999,
    },
    selectWrap: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-end',
        position: 'absolute',
        right: 0,
        top: 12 * scale,
        zIndex: 999,
    }
})